public class Solution23 {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode head = new ListNode();
        ListNode p = head;
        if (lists.length == 0)
            return head.next;
        if (lists.length == 1)
            return lists[0];
        ListNode m = lists[0];
        int index = 0;

        int curNum = lists.length;
        while (curNum > 1) {
            curNum = 0;
            for (int i = 0; i < lists.length; i++) {
                if (lists[i] != null) {
                    curNum++;
                    if (m == null || lists[i].val < m.val) {
                        m = lists[i];
                        index = i;
                    }
                }
            }
            p.next = m;
            if (m == null) {
                break;
            }
            m = m.next;
            lists[index] = m;
            p = p.next;
        }

        return head.next;
    }
}
